﻿using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Shweet.Engine;
using Shweet.Repository;

namespace Shweet.SPSolution.ShweetWriter
{
    public class ShweetWriter : System.Web.UI.WebControls.WebParts.WebPart
    {
        private TextBox _txtShweetText = null;
        private Button _btnShweetButton = null;
        private Label _shCount = null;

        protected override void CreateChildControls()
        {
            var shLabel = new Label {Text = "What are to doing today? "};
            Controls.Add(shLabel);
            
            _txtShweetText = new TextBox() {TextMode = TextBoxMode.MultiLine, Rows = 3, Width=200};
            Controls.Add(_txtShweetText);

            _shCount = new Label() { Text = "140", Width = 30,};
            Controls.Add(_shCount);

            _btnShweetButton = new Button() {Text = "Shweet"};
            _btnShweetButton.Click += new EventHandler(BtnShweetButtonClick);

            Controls.Add(_btnShweetButton);
        }

        void BtnShweetButtonClick(object sender, EventArgs e)
        {
            IShweetMessages shweetMessages = new ShweetMessages();
            var shweetWriter = new Writer(shweetMessages);
            if (!string.IsNullOrEmpty(_txtShweetText.Text))
                shweetWriter.Write(_txtShweetText.Text, HttpContext.Current.User.Identity.Name);
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            StringBuilder script = new StringBuilder();

            script.Append("<script type=\"text/javascript\">");
            script.Append("     var count = \"140\";");
            script.Append("     function limiter(){");
            script.Append("     var tex = document.getElementById(\"" + _txtShweetText.ClientID + "\").value;");
            script.Append("     var len = tex.length;");
            script.Append("     if(len > count){");
            script.Append("         tex = tex.substring(0,count);");
            script.Append("         document.getElementById(\"" + _txtShweetText.ClientID + "\").value=tex;");
            script.Append("         return false;");
            script.Append("     }");
            script.Append(" document.getElementById(\"" + _shCount.ClientID + "\").innerHTML = count-len;");
            script.Append("}");
            script.Append("</script>");

            this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "shweetjs", script.ToString());

            _txtShweetText.Attributes.Add("onkeyup", "javascript:limiter()");
            _txtShweetText.Attributes.Add("onkeydown", "javascript:limiter()");

        }
    }
}
